package com.fs.base.aspect;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.fs.base.pojo.Log;
import com.fs.base.repository.LogRepository;
import com.fs.base.utils.ApplicationUtils;

/**
 * @author TiddlerCJ
 * @desc http请求，日志拦截处理
 */
@Aspect
@Component
public class HttpAspect {
	@Pointcut("execution(* com..*.*Controller.*(..))")
	public void log(){}
	
	@Before("log()")
	public void Before(JoinPoint joinPoint){
		ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		if(StringUtils.isNotBlank(ApplicationUtils.userId())){
			Log log = new Log();
			log.setCreaterId(ApplicationUtils.userId());
			log.setLogIp(request.getRemoteAddr());
			log.setLogUrl(request.getRequestURL().toString());
			log.setLogData(JSON.toJSONString(request.getParameterMap()));
			log.setLogMethod(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
			LogRepository logRepository = (LogRepository) ApplicationUtils.getBean("logRepository");
			logRepository.save(log);
		}
	}
	
	@After("log()")
	public void After(){
	}
	
	@AfterReturning(pointcut="log()",returning="obj")
	public void onAfterReturning(Object obj){
		//System.out.println("response: "+ JSON.toJSONString(obj));
	}
}
